<template>
    <div class="attendance-setting">
        <el-tabs v-model="activeTab" @tab-click="onTabClick">
            <el-tab-pane label="今日考勤" name="today" />
            <el-tab-pane label="缺勤统计" name="absence" />
            <el-tab-pane label="历史考勤" name="history" />
            <el-tab-pane label="请假管理" name="leave" />
            <el-tab-pane label="离校管理" name="leaveSchool" />
            <el-tab-pane label="考勤时间设置" name="setting" />
        </el-tabs>

        <div class="filter-bar">
            <el-select v-model="timeType" placeholder="时间段" style="width: 120px; margin-right: 10px;">
                <el-option label="全部" value="" />
                <el-option label="上午" value="上午" />
                <el-option label="下午" value="下午" />
            </el-select>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
            <div style="flex: 1;"></div>
            <el-button type="primary" icon="Plus" @click="showAddTimeDialog">添加时间段</el-button>
        </div>

        <div class="result-info">查询结果：共计 {{ filteredTableData.length }} 条数据</div>

        <el-table :data="filteredTableData" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="period" label="时间段" width="200" align="center" />
            <el-table-column prop="startTime" label="开始时间" width="200" align="center" />
            <el-table-column prop="endTime" label="结束时间" width="200" align="center" />
            <el-table-column label="操作" width="200" align="center">
                <template #default="scope">
                    <el-button type="primary" text @click="handleEdit(scope.row)">
                        <el-icon>
                            <Edit />
                        </el-icon>编辑
                    </el-button>
                    <el-popconfirm title="确定删除此时间段吗?" @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button type="danger" text>
                                <el-icon>
                                    <Delete />
                                </el-icon>删除
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑时间段对话框 -->
        <el-dialog v-model="timeDialogVisible" :title="isEditMode ? '编辑时间段' : '添加时间段'" width="30%">
            <el-form :model="timeForm" label-width="100px" style="margin-top: 20px;">
                <el-form-item label="时间段">
                    <el-select v-model="timeForm.period" placeholder="请选择时间段">
                        <el-option label="上午" value="上午" />
                        <el-option label="下午" value="下午" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-time-picker v-model="timeForm.startTime" format="HH:mm" placeholder="请选择开始时间" />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-time-picker v-model="timeForm.endTime" format="HH:mm" placeholder="请选择结束时间" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="timeDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveTimeSettings">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 复制到剪贴板通知提示 -->
        <el-notification v-model:visible="notificationVisible" :duration="2000" type="success"
            :title="notificationTitle" :message="notificationMessage" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const activeTab = ref('setting')

// 监听路由变化高亮对应tab
watch(
    () => route.path,
    (path) => {
        if (path.includes('/main/attendance/manage')) {
            activeTab.value = 'today'
        } else if (path.includes('/main/attendance/absence')) {
            activeTab.value = 'absence'
        } else if (path.includes('/main/attendance/history')) {
            activeTab.value = 'history'
        } else if (path.includes('/main/attendance/leave')) {
            activeTab.value = 'leave'
        } else if (path.includes('/main/attendance/leaveSchool')) {
            activeTab.value = 'leaveSchool'
        } else if (path.includes('/main/attendance/setting')) {
            activeTab.value = 'setting'
        }
    },
    { immediate: true }
)

// 标签页切换
function onTabClick(tab: any) {
    if (tab.paneName === 'today') {
        router.push('/main/attendance/manage')
    } else if (tab.paneName === 'absence') {
        router.push('/main/attendance/absence')
    } else if (tab.paneName === 'history') {
        router.push('/main/attendance/history')
    } else if (tab.paneName === 'leave') {
        router.push('/main/attendance/leave')
    } else if (tab.paneName === 'leaveSchool') {
        router.push('/main/attendance/leaveSchool')
    } else if (tab.paneName === 'setting') {
        router.push('/main/attendance/setting')
    }
}

const timeType = ref('')
const tableData = ref([
    { id: 1, period: '上午', startTime: '8:00', endTime: '12:00' },
    { id: 2, period: '下午', startTime: '13:00', endTime: '16:30' }
])

// 根据筛选条件过滤数据
const filteredTableData = computed(() => {
    if (!timeType.value) {
        return tableData.value
    } else {
        return tableData.value.filter(item => item.period === timeType.value)
    }
})

// 添加/编辑对话框
const timeDialogVisible = ref(false)
const isEditMode = ref(false)
const timeForm = ref({
    id: 0,
    period: '',
    startTime: '',
    endTime: ''
})
const currentEditId = ref(0)

// 通知提示
const notificationVisible = ref(false)
const notificationTitle = ref('')
const notificationMessage = ref('')

function handleQuery() {
    // 查询逻辑，实际应用中可能需要调用API
}

function handleReset() {
    timeType.value = ''
}

function showAddTimeDialog() {
    isEditMode.value = false
    timeForm.value = {
        id: 0,
        period: '',
        startTime: '',
        endTime: ''
    }
    timeDialogVisible.value = true
}

function handleEdit(row: any) {
    isEditMode.value = true
    currentEditId.value = row.id
    timeForm.value = {
        id: row.id,
        period: row.period,
        startTime: row.startTime,
        endTime: row.endTime
    }
    timeDialogVisible.value = true
}

function handleDelete(row: any) {
    // 删除逻辑，实际应用中应该调用API
    tableData.value = tableData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
}

function saveTimeSettings() {
    // 保存设置，实际应用中应该调用API
    if (!timeForm.value.period || !timeForm.value.startTime || !timeForm.value.endTime) {
        ElMessage.warning('请填写完整的时间段信息')
        return
    }

    const formattedStartTime = formatTime(timeForm.value.startTime)
    const formattedEndTime = formatTime(timeForm.value.endTime)

    if (isEditMode.value) {
        // 编辑模式
        const index = tableData.value.findIndex(item => item.id === currentEditId.value)
        if (index !== -1) {
            tableData.value[index] = {
                id: currentEditId.value,
                period: timeForm.value.period,
                startTime: formattedStartTime,
                endTime: formattedEndTime
            }
            ElMessage.success('修改成功')
        }
    } else {
        // 添加模式
        const newId = tableData.value.length > 0
            ? Math.max(...tableData.value.map(item => item.id)) + 1
            : 1

        tableData.value.push({
            id: newId,
            period: timeForm.value.period,
            startTime: formattedStartTime,
            endTime: formattedEndTime
        })

        // 显示添加成功通知
        notificationTitle.value = '已添加到剪贴板'
        notificationMessage.value = '✓'
        notificationVisible.value = true
    }

    timeDialogVisible.value = false
}

// 格式化时间
function formatTime(timeValue: string | Date): string {
    if (!timeValue) return ''

    let hours = '00'
    let minutes = '00'

    if (typeof timeValue === 'string') {
        // 如果已经是字符串格式，直接返回
        return timeValue
    } else {
        // Date对象，格式化为HH:mm
        const date = new Date(timeValue)
        hours = date.getHours().toString().padStart(2, '0')
        minutes = date.getMinutes().toString().padStart(2, '0')
    }

    return `${hours}:${minutes}`
}
</script>

<style scoped>
.attendance-setting {
    background: #f7fafd;
    padding: 20px;
}

.filter-bar {
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
}

.result-info {
    margin-bottom: 10px;
    color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>